<template>
  <template v-if="$route.path.startsWith('/user')">
    <router-view />
  </template>
  <template v-else>
    <BasicLayout />
  </template>
</template>

<style></style>
<script setup lang="ts">
import BasicLayout from "@/layouts/BasicLayout.vue";
import { onMounted, ref } from "vue";
import "bytemd/dist/index.css";
import store from "@/store";

const doInit = () => {
  console.log("");
};

const uuid = (len: number, radix = 62) => {
  const chars =
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  const uuid = [];
  radix = radix || chars.length;

  for (let i = 0; i < len; i++) {
    uuid[i] = chars[0 | (Math.random() * radix)];
  }

  return uuid.join("");
};

const websocket = ref();
const token = ref();

const onOpen = () => {
  console.log("WebSocket连接成功，状态码：", websocket.value.readyState);
};
const onMessage = (event: any) => {
  console.log("WebSocket收到消息：", event.data);
  store.dispatch("questionSubmit/setQuestionList", JSON.parse(event.data));
};

const onError = () => {
  console.log("WebSocket连接错误，状态码：", websocket.value.readyState);
};
const onClose = () => {
  console.log("WebSocket连接关闭，状态码：", websocket.value.readyState);
};
const initWebSocket = () => {
  // 连接成功
  websocket.value.onopen = onOpen;
  // 收到消息的回调
  websocket.value.onmessage = onMessage;
  // 连接错误
  websocket.value.onerror = onError;
  // 连接关闭的回调
  websocket.value.onclose = onClose;
};

onMounted(() => {
  doInit();

  if ("WebSocket" in window) {
    // 这里Tool是我写的一个工具类的一个js，websocket的token生成就写在里面
    token.value = uuid(10);
    // 连接地址：ws://127.0.0.1:8880/ws/xxx
    websocket.value = new WebSocket(
      "ws://localhost:8100/api" + "/websocket/" + token.value
    );
    initWebSocket();

    // 关闭
    // websocket.value.close();
  } else {
    alert("当前浏览器不支持WebSocket");
  }
});
</script>
